import React, { Component } from 'react';
import {
	Text,
	View,
	Image,
	StyleSheet,
	FlatList,
	SectionList,
	RefreshControl,
	TouchableOpacity,
	DeviceEventEmitter,
	Platform,
	ScrollView,
	Alert,
	Linking,
} from 'react-native';
import { connect } from 'react-redux';
import NavigationBar from '../components/NavigationBar';
import TouchableOpenUrl from '../components/TouchableOpenUrl';
import Icon from 'react-native-vector-icons/Entypo';
import CitySectionList from '../components/CitySectionList';
import Panel from '../components/Panel';
import actioncoll from '../actions';
import Contacts from 'react-native-contacts';
const ITEM_HEIGHT = 50; //item的高度
const HEADER_HEIGHT = 24; //分组头部的高度
const SEPARATOR_HEIGHT = 0; //分割线的高度
const domain = "http://202.106.90.110:81"
class ContactsPage extends Component {
	constructor(props) {
		super(props);
		this.finalContactsArr = [];
	}

	componentWillMount() {
		this.props.GetContacts();
		Contacts.getAll((err, contacts) => {
			if (err) throw err;
			
			// contacts returned
			// alert(JSON.stringify(contacts))
		  })
		//   Contacts.getContactsMatchingString("王绪君", (err, contacts) => {
		// 	if (err) throw err;
			
		// 	// contacts matching "filter"
		// 	alert(JSON.stringify(contacts))
		//   })
	}

	_basicAlert = (title, msg, action) => {
		Alert.alert(title, msg, action, { cancelable: false });
	};
	openUrl(url) {
		Linking.canOpenURL(url)
			.then(supported => {
				if (!supported) {
					alert("Can't handle url: " + url);
				} else {
					return Linking.openURL(url);
				}
			})
			.catch(err => alert('An error occurred', err));
	}
	save(contact){
		var birthday = new Date(contact.BIRTHDAY)
		
		var b = {"year": birthday.getFullYear(), "month": birthday.getMonth(), "day": birthday.getDate() }
		alert(JSON.stringify(b))
		var newPerson = {
			company: "",
			emailAddresses: [{
			  label: "work",
			  email: contact.MAIL,
			}],
			phoneNumbers: [{
				label: "mobile",
				number: contact.MOBILE,
			  },
			  {
				label: "work",
				number: contact.WORK_TEL,
			  }],
			  familyName: "",
			  givenName: contact.CONTACT_NAME,
			  jobTitle: contact.POST,
			  middleName: "",
			  birthday: b,
			  thumbnailPath: domain + contact.IMAGE_PATH
		  }
		  Contacts.addContact(newPerson, (err) => {
			if (err) {
				alert(JSON.stringify(err))
			};
			alert('保存成功')
			
		  })
	}

	render() {
		if (this.props.contacts) {
			this.finalContactsArr = this.props.contacts;
			console.log(this.finalContactsArr);
		}
		
		return (
			<View style={styles.container}>
				<NavigationBar title="通讯录" />

				<ScrollView>
					{this.finalContactsArr.map((org, i) => {
						return (
							<Panel title={org.ORG_NAME} key={org.ORG_NAME}>
								{org.items.map((contact, i) => {
									return (
										<View style={[styles.contact, styles.flexRow]} key={contact.CONTACT_NAME}>
											<View style={[styles.Separator]} />
											<Image style={[styles.Separator,{width: 70}]} source={{uri: domain + contact.IMAGE_PATH}}></Image>
											<View style={[styles.flexColumn, styles.title]}>
												<Text>{contact.CONTACT_NAME}</Text>
												<Text>{contact.POST}</Text>
												<TouchableOpacity onPress={() => this.save(contact)}>
													<Icon style={[styles.icon]} size={15} name="save" />
												</TouchableOpacity>
											</View>
											<View style={[styles.flexColumn, styles.title]}>
												<TouchableOpacity onPress={() => this.openUrl('tel:' + contact.MOBILE)}>
													<Icon style={styles.icon} size={15} name="mobile">
														{contact.MOBILE}
													</Icon>
												</TouchableOpacity>
												<TouchableOpacity
													onPress={() => this.openUrl('smsto:' + contact.MOBILE)}
												>
													<Icon style={styles.icon} size={15} name="new-message">
														{contact.MOBILE}
													</Icon>
												</TouchableOpacity>
												<TouchableOpacity
													onPress={() => this.openUrl('tel:' + contact.WORK_TEL)}
												>
													<Icon style={styles.icon} size={15} name="landline">
														{contact.WORK_TEL}
													</Icon>
												</TouchableOpacity>
												<TouchableOpacity
													onPress={() => this.openUrl('mailto:' + contact.MAIL)}
												>
													<Icon style={styles.icon} size={15} name="mail">
														{contact.MAIL}
													</Icon>
												</TouchableOpacity>
											</View>
										</View>
									);
								})}
							</Panel>
						);
					})}
				</ScrollView>
			</View>
		);
	}
	// async getCityInfos() {
	//     let data = await require('../../res/data/city.json');
	//     let jsonData = data.data
	//     //每组的开头在列表中的位置
	//     let totalSize = 0;
	//     //SectionList的数据源
	//     let cityInfos = [];
	//     //分组头的数据源
	//     let citySection = [];
	//     //分组头在列表中的位置
	//     let citySectionSize = [];
	//     for (let i = 0; i < jsonData.length; i++) {
	//         citySectionSize[i] = totalSize;
	//         //给右侧的滚动条进行使用的
	//         citySection[i] = jsonData[i].title;
	//         let section = {}
	//         section.key = jsonData[i].title;
	//         section.data = jsonData[i].city;
	//         for (let j = 0; j < section.data.length; j++) {
	//             section.data[j].key = j
	//         }
	//         cityInfos[i] = section;
	//         //每一项的header的index
	//         totalSize += section.data.length + 1
	//     }
	//     this.setState({ data: cityInfos, sections: citySection, sectionSize: citySectionSize })
	// }

	// constructor(props) {
	//     super(props);
	//     this.state = {
	//         data: [],
	//         sections: [],
	//         sectionSize: []
	//     }
	//     this.getCityInfos()
	// }

	// render() {
	//     if (this.state.data.length > 0) {
	//         return (
	//             <View>
	//                 <NavigationBar
	//                     title="主页"
	//                 />
	//                 <View>
	//                     <SectionList
	//                         ref='list'
	//                         enableEmptySections
	//                         renderItem={this._renderItem}
	//                         renderSectionHeader={this._renderSectionHeader}
	//                         sections={this.state.data}
	//                         getItemLayout={this._getItemLayout} />

	//                     <CitySectionList
	//                         sections={this.state.sections}
	//                         onSectionSelect={this._onSectionselect} />
	//                 </View>
	//             </View>
	//         )
	//     } else {
	//         return <View />
	//     }
	// }

	// //这边返回的是A,0这样的数据
	// _onSectionselect = (section, index) => {
	//     //跳转到某一项

	//     this.refs.list.scrollToIndex({ animated: true, index: this.state.sectionSize[index] })
	// }

	// _getItemLayout(data, index) {
	//     let [length, separator, header] = [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER_HEIGHT];
	//     return { length, offset: (length + separator) * index + header, index };
	// }

	// _renderItem = (item) => {
	//     return (
	//         <View style={styles.itemView}>
	//             <Text style={{ marginLeft: 30, fontSize: 16, color: '#333' }}>
	//                 {item.item.city_child}
	//             </Text>
	//             <Text style={{ marginLeft: 25, fontSize: 15, color: '#999' }}>
	//                 {item.item.city_parent}
	//             </Text>
	//             <Text style={{ marginLeft: 25, fontSize: 13, color: '#999' }}>
	//                 {item.item.provcn}
	//             </Text>
	//         </View>
	//     )
	// }

	// _renderSectionHeader = (section) => {
	//     return (
	//         <View style={styles.headerView}>
	//             <Text style={styles.headerText}>{section.section.key}</Text>
	//         </View>
	//     )
	// }
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#f4f7f9',
		// paddingTop : 30 //if hidenavbar=false
	},
	headerView: {
		justifyContent: 'center',
		height: HEADER_HEIGHT,
		paddingLeft: 20,
		backgroundColor: '#eee',
	},
	headerText: {
		fontSize: 15,
		fontWeight: 'bold',
		color: '#3cb775',
	},
	itemView: {
		flexDirection: 'row',
		padding: 12,
		alignItems: 'center',
		height: ITEM_HEIGHT,
	},
	flexRow: {
		flexDirection: 'row',
	},
	flexColumn: {
		flexDirection: 'column',
	},
	Separator: {
		width: 3,
		height: '100%',
		backgroundColor: 'cyan',
	},
	contact: {
		marginBottom: 3,
		justifyContent: 'flex-start',
		alignItems: 'center',
		margin: 5,
	},
	title: {
		flex: 1,
		justifyContent: 'space-between',
		margin: 10,
	},
	icon: {
		height: 20,
	},
});

export default connect(
	state => ({
		contacts: state.contactReducer.contacts,
	}),
	dispatch => ({
		GetContacts: () => dispatch(actioncoll.contact.GetContacts()),
	})
)(ContactsPage);
